﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace Carer.Data.Json
{
    public class MyDateTimeConverter : DateTimeConverterBase
    {
        private string format = "yyyy-MM-dd HH:mm:ss";
        public MyDateTimeConverter()
        {

        }
        public MyDateTimeConverter(string format)
        {
            if (!string.IsNullOrWhiteSpace(format))
            {
                this.format = format;
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return DateTime.Parse(reader.Value.ToString());
            }

            return null;
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime)
            {
                DateTime dt = (DateTime)value;
                writer.WriteValue(dt.ToString(this.format));
            }
        }
    }
}
